
/*
给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
输入：head = [1,2,3,4,5], n = 2
输出：[1,2,3,5]
示例 2：

输入：head = [1], n = 1
输出：[]
示例 3：

输入：head = [1,2], n = 1
输出：[1]

*/


function ListNode(val, next) {
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
}

/**
 * @param {number[]} head
 * @return {ListNode}
 */
const init = (head) => {
    let first = null, p = null
    for (const item of head) {
        const node = new ListNode(item)
        if (!first) {
            first = node
            p = first
            continue
        }
        p.next = node
        p = node
    }
    return first
}
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {number[]} head
 * @param {number} n
 * @return {ListNode}
 */
var removeNthFromEnd = function (head, n) {
    const node = init(head)
    let fast = node, low = fast

    if (n >= head.length) {
        return
    }

    let n1 = n
    do {
        fast = fast.next
        n1--
    } while (n1 > 0)


    while (fast.next != null) {
        fast = fast.next
        low = low.next
    }
    low.next = low.next.next

    return node
};

console.log(removeNthFromEnd([1, 2, 3, 4, 5, 8, 9, 7, 5, 3, 7], 4))
console.log(removeNthFromEnd([1], 1))
console.log(removeNthFromEnd([1, 2], 1))
console.log('end');